package com.controller;

import com.google.code.kaptcha.Constants;
import com.mapper.SystemMessageMapper;
import com.mapper.UserMapper;
import com.message.UserMessage;
import com.model.ResponseMsg;
import com.model.SystemMessage;
import com.model.User;
import com.util.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Controller
@PropertySource("classpath:message.properties")
public class IndexController {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private UserMessage userMessage;

    @Autowired
    private SystemMessageMapper systemMessageMapper;


    @Autowired
    private Environment env;
    // inject via application.properties
    @Value("${welcome.message:test}")
    private String message = "Hello World";

    @RequestMapping("/loginSubmit")
    @ResponseBody
    public ResponseMsg loginSubmit(@RequestParam(required = true) String userName, @RequestParam(required = true) String password, HttpSession session) {
        ResponseMsg msg = new ResponseMsg();
        User user = new User();
        user.setUserName(userName);
        List<User> userList = userMapper.getUserByCondition(user);

        if ((userList.size() != 1 || (((User) userList.get(0)).getStatus() != 1))) {
            msg.setData("您输入的账号或者密码有问题。");
            return msg;
        }
        User userTemp = userList.get(0);
        if (!userTemp.getPassword().equalsIgnoreCase(MD5Util.MD5(password))) {
            msg.setData("您输入的账号或者密码有问题。");
            return msg;
        }
        //修改登录时间
        userTemp.setUpdateTime(DateUtils.getFormtDate());
        userMapper.updateUserInfo(userTemp);
        session.setAttribute(ConstantUtil.loginSession, userTemp);
        msg.setStatus(ResponseMsg.success);
        msg.setData(userTemp);
        return msg;
    }


    @RequestMapping("/findPassword")
    @ResponseBody
    public ResponseMsg findPassword(@RequestParam(required = true) String userName) {
        ResponseMsg msg = new ResponseMsg();
        User user = new User();
        user.setUserName(userName);
        List<User> userList = userMapper.getUserByCondition(user);

        if (userList.size() != 1 || (((User) userList.get(0)).getStatus() != 1)) {
            msg.setData("您的账号有问题，请联系客服！");
            return msg;
        }

        User userTemp = userList.get(0);

        EmailUtil.sendEmail(userTemp.getEmail());

        msg.setStatus(ResponseMsg.success);
        msg.setData(userTemp);
        return msg;
    }

    @RequestMapping("/registerView")
    public String registerView(HttpServletRequest request) {
        return "register";
    }

    @RequestMapping("/register")
    @ResponseBody
    public ResponseMsg register(HttpServletRequest request, HttpSession session) {
        String userName = request.getParameter("userName");
        String birthday = request.getParameter("birthday");
        String sex = request.getParameter("sex");
        String lastName = request.getParameter("lastName");
        String firstName = request.getParameter("firstName");
        String password = request.getParameter("password");
        String email = request.getParameter("email");
        String phone = request.getParameter("phone");
        String verifyCode = request.getParameter("verifyCode");
        String agentCode = request.getParameter("agentCode");
        String realName = lastName + firstName;

        String code = (String)session.getAttribute(Constants.KAPTCHA_SESSION_KEY);
        ResponseMsg msg = new ResponseMsg();

        if (StringUtils.isEmpty(userName)) {
            msg.setData("用户名不能为空!");
            return msg;
        }
        if (userName.length() < 6) {
            msg.setData("用户名不能少于6位！");
            return msg;
        }

        if (StringUtils.isEmpty(password)) {
            msg.setData("密码不能为空!");
            return msg;
        }
        if (password.length() < 6) {
            msg.setData("密码不能少于6位！");
            return msg;
        }
        if (!PhoneFormatCheckUtils.isPhoneLegal(phone)) {
            msg.setData("手机格式不正确！");
            return msg;
        }

        if(!verifyCode.equalsIgnoreCase(code)){
            msg.setData("验证码错误!");
            return msg;
        }


        User user = new User();
        user.setUserName(userName);
        user.setAgentCode(agentCode);
        user.setEmail(email);
        user.setPassword(MD5Util.MD5(password));
        user.setRealName(realName);
        user.setPhone(phone);
        user.setBirthday(birthday);
        user.setRealName(realName);
        user.setSex(Integer.parseInt(sex));
        user.setCreateTime(DateUtils.getFormtDate());
        user.setUserLevel(1);
        user.setPhoneStatus(1);
        user.setEmailStatus(1);
        user.setUpdateTime(DateUtils.getFormtDate());
        user.setUserBalance("0");
        user.setDepositGroupId(2);
        user.setLastloginIp(ConstantUtil.getIpAddr(request));

        List<User> userList = userMapper.getUserByCondition(user);
        if (userList.size() != 0) {
            msg.setData("用户名不能重复!");
            return msg;
        }

        userMapper.addUser(user);

        session.setAttribute(ConstantUtil.loginSession, user);
        msg.setStatus(ResponseMsg.success);

        return msg;
    }


    @RequestMapping("/login")
    public String login(Map<String, Object> model) {
        model.put("message", this.message);
        model.put("user", new User());
        System.out.print("userMessage.getEmail():" + userMessage.getEmail());
        return "login";
    }


    @RequestMapping("/logout")
    public String logout(Map<String, Object> model,HttpSession session) {
        session.removeAttribute(ConstantUtil.loginSession);
        return "index";
    }





    @RequestMapping("/index")
    public String index(Map<String, Object> model,HttpSession session) {
        model.put("message", this.message);
        //显示系统时间
        model.put("currentTime",DateUtils.getFormtDate());
        session.setAttribute("currentTime",DateUtils.getFormtDate());

        User user = (User) session.getAttribute(ConstantUtil.loginSession);
        if(user != null){
            SystemMessage message = new SystemMessage();
            message.setUserId(user.getUserId());
            message.setType(1);
            List<SystemMessage> list = systemMessageMapper.getAllMessage( message );
            List<SystemMessage> unreadList = list.stream().filter(item -> (item.getStatus()==0)).collect(Collectors.toList());
            session.setAttribute("unreadMessageNumber",unreadList.size());
        }
        return "index";
    }
    public UserMapper getUserMapper() {
        return userMapper;
    }
    public void setUserMapper(UserMapper userMapper) {
        this.userMapper = userMapper;
    }
    public String getMessage() {
        return message;
    }
    public void setMessage(String message) {
        this.message = message;
    }
    public UserMessage getUserMessage() {
        return userMessage;
    }
    public void setUserMessage(UserMessage userMessage) {
        this.userMessage = userMessage;
    }
    public Environment getEnv() {
        return env;
    }
    public void setEnv(Environment env) {
        this.env = env;
    }

}
